package jj.fly.activiti.leavebill.controller;

import jj.fly.activiti.leavebill.service.ILeaveBillService;
import jj.fly.activiti.leavebill.utils.ManagerTaskHandler;
import jj.fly.activiti.leavebill.vo.SubmitTaskVo;
import jj.fly.activiti.leavebill.domain.Employee;
import jj.fly.activiti.leavebill.domain.LeaveBill;
import jj.fly.activiti.leavebill.domain.custom.LeaveBillCustom;
import jj.fly.activiti.leavebill.service.IWorkflowService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * Author: jiangjun
 * Date: 2018/5/9
 * Time: 上午9:22
 * Description:
 */
@Controller
@RequestMapping("/workflow")
public class WorkflowController {

    @Autowired
    private IWorkflowService workflowService;

    @Autowired
    private ILeaveBillService leaveBillService;

    @GetMapping("/workflowUI")
    public String workflowUI(Model model) {
        // 查询部署对象信息
        List<Deployment> deploymentList = workflowService.getDeploymentList();
        model.addAttribute("deploymentList", deploymentList);
        // 查询流程定义信息
        List<ProcessDefinition> processDefinitionList = workflowService.getProcessDefinitionList();
        model.addAttribute("processDefinitionList", processDefinitionList);
        return "workflow/workflow";
    }

    @RequestMapping("/deploy")
    public String deploy(@RequestParam(name = "workflowFile", required = false) MultipartFile workflowFile,
                         String name,
                         HttpServletResponse response) throws Exception {
        workflowService.deploy(name, workflowFile.getBytes());
        return "redirect:workflowUI";
    }

    @GetMapping("/{deployId}/{imageName}/viewImage")
    public void viewImage(@PathVariable("deployId") String deployId,
                          @PathVariable("imageName") String imageName,
                          HttpServletResponse response) throws IOException {
        InputStream inputStream = workflowService.getImageInputStream(deployId, imageName);
        ServletOutputStream outputStream = response.getOutputStream();
        for (int b = -1; (b = inputStream.read()) != -1; ) {
            outputStream.write(b);
        }
        outputStream.close();
        inputStream.close();
    }

    @GetMapping("/{deployId}/delete")
    public String delete(@PathVariable("deployId") String deployId){
        workflowService.deleteProcessDefinitionByDeployId(deployId);
        return "redirect:/workflow/workflowUI";
    }

    /**
     * 启动流程实例
     * @return
     */
    @GetMapping("/{leaveBillId}/startProcess")
    public String startProcess(@PathVariable("leaveBillId") Integer leaveBillId){
        // 更新请假状态，启动流程实例并关联请假业务
        workflowService.startProcess(leaveBillId);
        return "";
    }

    @GetMapping("/listTask")
    public String listTask(HttpServletRequest request, Model model){
        Employee currentUser = (Employee) request.getSession().getAttribute("current_user");
        List<Task> taskList = workflowService.getTaskListByEmployeeName(currentUser.getName());
        model.addAttribute("taskList", taskList);
        return "workflow/task";
    }

    /**
     * 根据taskId获取任务的form key，从而进行重定向
     * @param taskId
     * @param model
     * @return
     */
    @GetMapping("/{taskId}/taskFormUI")
    public String taskFormUI(@PathVariable("taskId") String taskId,
                             Model model){
        String url = workflowService.getTaskFormKeyByTaskId(taskId);
        url += "/" + taskId;
        model.addAttribute("url", url);
        return "redirect:/" + url;
    }

    @GetMapping("/audit/{taskId}")
    public String audit(@PathVariable("taskId") String taskId, Model model){
        // 使用taskIdc查询请假单id，从而获取请假单信息
        LeaveBill leaveBill = workflowService.getLeaveBillByTaskId(taskId);
        LeaveBillCustom leaveBillCustom = new LeaveBillCustom();
        BeanUtils.copyProperties(leaveBill, leaveBillCustom);
        leaveBillCustom.setComment("");
        model.addAttribute("leaveBill", leaveBillCustom);

        // 根据taskIdc查询ProcessDefinitionEntity对象，获取任务完成后的连线名称
        List<String> outcomeList = workflowService.getOutcomeListByTaskId(taskId);
        model.addAttribute("outcomeList", outcomeList);

        // 查询历史审核信息
        List<Comment> commentList = workflowService.getCommentByTaskId(taskId);
        model.addAttribute("commentList", commentList);
        model.addAttribute("taskId", taskId);
        return "workflow/taskForm";
    }

//    @Autowired
//    private ManagerTaskHandler handler;

    @PostMapping("/submitTask")
    public String submitTask(SubmitTaskVo vo){
        //handler.test();
        workflowService.submitTask(vo);
        return "redirect:/workflow/listTask";
    }

    @GetMapping("/{id}/viewHisComment")
    public String viewHisComment(@PathVariable("id") Integer id, Model model){
        LeaveBill leaveBill = leaveBillService.getDataById(id);
        model.addAttribute("leaveBill", leaveBill);
        // 根据请假单id，查询历史批注信息
        List<Comment> commentList = workflowService.getCommentByLeaveBillId(id);
        model.addAttribute("commentList", commentList);
        return "workflow/taskFormHis";
    }

    @GetMapping("/{taskId}/viewCurrentImage")
    public String viewCurrentImage(@PathVariable("taskId") String taskId, Model model){
        // 查看流程图
        ProcessDefinition processDefinition = workflowService.getProcessDefinitionByTaskId(taskId);
        String deployId = processDefinition.getDeploymentId();
        String imageName = processDefinition.getDiagramResourceName();
        model.addAttribute("deployId", deployId);
        model.addAttribute("imageName", imageName);

        // 查看当前活动，获取对应的x，y，width，height
        Map<String, Object> map = workflowService.getCoordingByTaskId(taskId);
        model.addAttribute("map", map);
        return "workflow/currentImage";
    }
}
